package com.icecold.utils.file;

import com.icecold.utils.StringUtils;
import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import cn.hutool.core.io.FileUtil;


/**
 * 图片压缩
 **/
public class ImageCompressor {

    /**
     * 缩略图生成，处理一些较大的图片，防止占用太多的网络资源
     */
    public static void thumbnails(File imageFile, int maxWidth, int maxHeight, String outputFormat) {
        if (imageFile == null || !imageFile.exists() || (maxWidth <= 0 && maxHeight <= 0)) {
            return;
        }
        String suffix = FileUtil.getSuffix(imageFile.getName());
        // 只处理可以压缩的图片，如gif图片压缩后会出现黑色背景的情况
        if (!StringUtils.inString(suffix, "png", "jpg", "jpeg", "bmp", "ico")) {
            return;
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            Thumbnails.Builder<BufferedImage> bilder = Thumbnails.of(bufferedImage);
            if (bufferedImage != null) {
                if (maxWidth > 0) {
                    if (bufferedImage.getWidth() <= maxWidth) {
                        bilder.width(bufferedImage.getWidth());
                    } else {
                        bilder.width(maxWidth);
                    }
                }
                if (maxHeight > 0) {
                    if (bufferedImage.getHeight() <= maxHeight) {
                        bilder.height(bufferedImage.getHeight());
                    } else {
                        bilder.height(maxHeight);
                    }
                }
                if (StringUtils.isNotBlank(outputFormat)) {
                    bilder.outputFormat(outputFormat);
                }
                bilder.toFile(imageFile);
            }
        } catch (IOException e) {
            System.out.println("图片压缩失败：" + imageFile.getAbsoluteFile());
        }
    }

    public static void main(String[] args) {
        thumbnails(new File("D://image/1.jpg"),1000,-1,null);
    }
}
